const app = getApp();
Page({
  data: {
    curGoods:{},
    curNum:1,
    imgBaseUrl: app.globalData.imgBaseUrl,
    commnetValue: "",
    starNum: 5,
    salePrice: null,
    amount: null,
    goodsName: null,
    totalPrice: null,
    selected: false,
    hasList: true,
    userInfo: {},
    goodsList: [],
    carts: [], // 购物车列表
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认全选
    obj: {
      name: "hello"
    },
    navbar: ['产品', '评价', '平台信息', '购买须知'],
    currentTab: 0,
    category: [{
        name: '砂石',
        id: 'shashi'
      },
      {
        name: '水泥',
        id: 'shuini'
      },
      {
        name: '水泥砖',
        id: 'zhuan'
      },
      {
        name: '加气块',
        id: 'kuai'
      },

    ],
    curIndex: 0,
    detail: [],

    isScroll: false,
    toView: 'shashi',
    starDesc: '非常满意，无可挑剔',
    stars: [{
      lightImg:'/images/star/star_light.png',
      blackImg:'/images/star/star_black.png',
      flag: 1,
      message:'非常不满意，各方面都很差'
    }, {
      lightImg:'/images/star/star_light.png',
      blackImg:'/images/star/star_black.png',
      flag: 1,
      message: '不满意，比较差'
    }, {
      lightImg:'/images/star/star_light.png',
      blackImg:'/images/star/star_black.png',
      flag: 1,
      message:'一般，还要改善'
    }, {
      lightImg:'/images/star/star_light.png',
      blackImg:'/images/star/star_black.png',
      flag: 1,
      message:'比较满意，仍要改善'
    }, {
      lightImg:'/images/star/star_light.png',
      blackImg:'/images/star/star_black.png',
      flag: 1,
      message:'非常满意，无可挑剔'
    }],
    assessLists: ['意见很有帮助', '态度非常好', '非常敬业', '非常专业认真', '回复很及时', '耐心细致']
  },

  navbarTap: function(e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
    //全局变量
    app.globalData.currentTab = e.currentTarget.dataset.idx;
  },
  onShow() {
    this.setData({
      currentTab: app.globalData.currentTab
    })
  },
  switchTab(e) {
    let that = this;
    let carts = that.data.carts;
    wx.request({
      url: app.globalData.baseUrl + "/goods/type",
      data: {
        type: e.currentTarget.dataset.name
      },
      header: {
        "cookie": "JESSIONID=" + that.data.userInfo.sessionId,
      },
      method: "GET",
      success(res) {
        console.log(res);
        res.data.forEach((r_value, r_index, r_arr) => {
            carts.forEach((c_value, c_index, c_arr) => {
              if (r_value.id == c_value.id) {
                  r_arr[r_index] = c_value;
              } else {
                r_value.num = 1;
              }
            });
        });
        that.setData({
          goodsList: res.data
        });
      },
      fail(err) {
        wx.showToast({
          title: '服务器异常！',
          icon: 'loading',
          duration: 1500
        });
        console.log(err);
      }
    })
    const self = this;
    this.setData({
      isScroll: true
    })
    setTimeout(function() {
      self.setData({
        toView: e.target.dataset.id,
        curIndex: e.target.dataset.index
      })
    }, 0)
    setTimeout(function() {
      self.setData({
        isScroll: false
      })
    }, 1)

  },
  onShow() {
    this.getTotalPrice();
  },
  /**
   * 当前商品选中事件
   */
  selectGoods(e) {
    let that = this;
    let carts = that.data.carts;
    let goods = {};
    let goodsList = that.data.goodsList;
    goodsList[e.currentTarget.dataset.index].selected = true;
    that.setData({
      goodsList: goodsList
    })
    let item = e.currentTarget.dataset.item;
    item.selected = true;
    goods = item;
    let index = carts.push(goods);
    carts[index - 1].selected = true;
    carts[index - 1].num = that.data.curNum
    that.setData({
      carts: carts,
    });
    that.getTotalPrice();
  },
  /**
   * 当前商品取消事件
   */
  cancleGoods(e) {
    let that = this;
    let carts = that.data.carts;
    let item = e.currentTarget.dataset.item;
    let goodsList = that.data.goodsList;
    goodsList[e.currentTarget.dataset.index].selected = false;
    goodsList[e.currentTarget.dataset.index].num = 1;
    that.setData({
      goodsList: goodsList
    });
    item.selected = false;
    carts.forEach((value, index, array) => {
      if (value.id == item.id) {
        array.splice(index, 1);
        return;
      }
    });
    that.getTotalPrice();
  },
    // this.setData({
      
    //   goodsName: carts[index].goodsName,
    //   salePrice: carts[index].salePrice,
    //   amount: carts[index].amount
    // });

  /**
   * 快捷选择评论
   */
  switchComment(e) {
    console.log(e);
    this.setData({
      commentValue: e.currentTarget.dataset.item
    });
  },
  /**
   * 删除购物车当前商品


  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    let carts = this.data.carts;
    let goodsList = this.data.goodsList;
    carts.forEach((c_value,c_index)=>{
      if(c_value.id == item.id) {
        if (c_value.num < item.amount) {
          c_value.num++;
          goodsList.forEach((g_value, g_index) => {
            if (g_value.id == item.id) {
              g_value.num = c_value.num;
              that.setData({
                goodsList: goodsList
              });
            }
          });
        } else {
          wx.showToast({
            title: '已达商品最大数量！',
            duration: 2000
          });
          return;
        }
      }
    });
    this.getTotalPrice();
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    let that = this;
    let item = e.currentTarget.dataset.item;
    let carts = this.data.carts;
    let goodsList = this.data.goodsList;
    carts.forEach((c_value, c_index) => {
      if (c_value.id == item.id) {
        if (c_value.num > 0) {
          c_value.num--;
          goodsList.forEach((g_value, g_index) => {
            if (g_value.id == item.id) {
              g_value.num = c_value.num;
              that.setData({
                goodsList: goodsList
              });
            }
          });
        } else {
          wx.showToast({
            title: '已达商品最小数量！',
            duration: 2000
          });
          return;
        }
      }
    });
    this.getTotalPrice();
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let that = this;
    let carts = this.data.carts; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) {
      // 循环列表得到每个数据
      total += carts[i].num * carts[i].salePrice + carts[i].deliverCost; // 所有价格加起
    }
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },
  /**
   * 跳转到提交商品页面
   */
  tijiao: function() {
    let that = this;
    if(that.data.carts.length == 0) {
      wx.showModal({
        title: '提示',
        content: '尚未选择商品！',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            return;
          }
        }
      })
    } else {
      wx.setStorageSync("carts", that.data.carts);
      wx.navigateTo({
        url: '/pages/yuding/order/order'
      });
    }
  },

  // 选择评价星星
  starClick: function(e) {
    var that = this;
    for (var i = 0; i < that.data.stars.length; i++) {
      var allItem = 'stars[' + i + '].flag';
      that.setData({
        [allItem]: 2
      })
    }
    var index = e.currentTarget.dataset.index;
    that.setData({
      starNum: index + 1,
    })
    console.log("star", e.currentTarget.dataset.index);
    for (var i = 0; i <= index; i++) {
      var item = 'stars[' + i + '].flag';
      that.setData({
        [item]: 1
      })
    }
    this.setData({
      starDesc: this.data.stars[index].message
    })
  },

  /**
   * 提交评价
   */
  submitEvaluation: function(e) {
    console.log(e);
    let that = this;
    wx.request({
      url: app.globalData.baseUrl + "/comments",
      header: {
        "cookie": "JESSIONID=" + that.data.userInfo.sessionId
      },
      method: "POST",
      data: {
        delivery: that.data.starNum,
        content: e.detail.value.commentValue,
        userId: that.data.userInfo.userId
      },
      success(res) {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '感谢您的评价！',
            icon: 'success',
            duration: 1500
          });
        } else {
          wx.showToast({
            title: '服务器异常！',
            icon: 'loading',
            duration: 1500
          });
        }
        console.log("commentRes", res);
      },
      fail(err) {
        wx.showToast({
          title: '服务器异常！',
          icon: 'loading',
          duration: 1500
        });
        console.log("commentErr", err);
      }
    })
    wx.showToast({
      title: '感谢您的评价！',
      icon: "success",
      duration: 1500
    })
  },
  onLoad: function(event) {
    let that = this;
    that.setData({
      userInfo: wx.getStorageSync("userInfo")
    });
    /**
     * 获取商品列表
     */
    wx.request({
      url: app.globalData.baseUrl + "/goods/type",
      data: {
        type: that.data.category[0].name
      },
      header: {
        "cookie": "JESSIONID=" + that.data.userInfo.sessionId
      },
      method: "GET",
      success(res) {
        console.log(res);
        res.data.forEach(value=>{
          value.num = 1;
        });
        that.setData({
          goodsList: res.data
        });
      },
      fail(err) {
        wx.showToast({
          title: '服务器异常！',
          icon: 'loading',
          duration: 1500
        });
        console.log(err);
      }
    })
  }

})